import sys
import time
from decimal import Decimal
import loger
import sqlite3
import pathlib
from decimal import Decimal

root=pathlib.Path(__file__).parent
db=sqlite3.connect(str(root/"statistics.db"))
cur = db.cursor()
log = loger.Logger('statistics',StreamLevel='info',FileLevel='info').logger

subject={       #年级，科目，卷面总分
    "七年级":{
        "语文":100
        ,"数学":100
        ,"英语":100
        ,"道法":100
        ,"历史":100
        ,"地理":100
        ,"生物":100
        }
    ,"八年级":{
        "语文":100
        ,"数学":100
        ,"英语":100
        ,"道法":100
        ,"历史":100
        ,"地理":100
        ,"物理":100
        ,"生物":100
        }
    ,"九年级":{
        "语文":100
        ,"数学":100
        ,"英语":100
        ,"道法":100
        ,"历史":100
        ,"物理":100
        ,"化学":100
        }
}
weight={
        "语文":Decimal("1")
        ,"数学":Decimal("1")
        ,"英语":Decimal("1")
        ,"道法":Decimal("0.4")
        ,"历史":Decimal("0.4")
        ,"地理":Decimal("0.3")
        ,"物理":Decimal("0.5")
        ,"生物":Decimal("0.4")
        ,"化学":Decimal("0.3")
}
EexcellenceRateEdge=0.8
PassRateEdge=0.6
LowScoreRateEdge=0.3
MissingExamination = 0 #缺考处理 None：忽略， 0：0分处理
CheckMaxPoint=100 #录入时检查的最高分（超过时报错）
colnames=["学籍号","学校","年级","班级","姓名"]

subject_alias={
    "道德与法治":"道法",
}
SubjectMerger={
    "英语":["英语卷面","英语口语"],
    "生物":["生物卷面","生物实验"],
    "物理":["物理卷面","物理实验"],
    "化学":["化学卷面","化学实验"]
    }

#录入科目整理
for i in subject: 
    for j in subject[i]:
        if(j in list(SubjectMerger.keys())) :
            colnames+=SubjectMerger[j]
        else:
            colnames.append(j)
templist=colnames
colnames=list(set(colnames))
colnames.sort(key=templist.index)
templist=None
###

###计算科目整理
subjectList=[]
for i in subject:
    subjectList+=subject[i]
st=subjectList
subjectList=list(set(subjectList))
subjectList.sort(key=st.index)
st=None
###
titleRow=0 #标题所在行
studentIDLen=14 #学籍号长度
zone={
"鲁甸县崇文高级中学":"A",
"鲁甸县茨院中学":"B",
"鲁甸县第二中学":"A",
"鲁甸县第一中学":"A",
"鲁甸县火德红中学":"D",
"鲁甸县江底中学":"C",
"鲁甸县乐红中学":"D",
"鲁甸县龙泉中学":"C",
"鲁甸县龙树中学":"C",
"鲁甸县卯家湾九年一贯制学校":"B",
"鲁甸县南城中学":"A",
"鲁甸县水磨九年一贯制学校":"D",
"鲁甸县水磨中学":"D",
"鲁甸县梭山中学":"D",
"鲁甸县桃源中学":"B",
"鲁甸县文屏中学":"B",
"鲁甸县小寨中学":"C",
"鲁甸县新街中学":"C",
"昭通市鲁甸弘清中学":"E",
"test":"F",
}
def _exit(msg="",waittime=3):
    for i in range(waittime+1):
        print('\r',f"{msg} {waittime-i}秒后退出",end='')
        time.sleep(1)
    sys.exit()

def DataConversion(subject_,grade_,value1,value2):
    if(subject_ in subject[grade_]):
        maxpoint=subject[grade_][subject_]
    else:
        maxpoint=999
    if(subject_ in list(SubjectMerger.keys())):
        if(value1=="" or value1 is None):
            if(MissingExamination is None):
                return (True ,MissingExamination)
            else:
                value1=0
        if(value2=="" or value2 is None):
            value2=0
        try:
            float(value1)
        except:
            return (False,"数据1错误")
        try:
            float(value2)
        except:
            return (False,"数据2错误")
        v_=Decimal(str(value1))+Decimal(str(value2))
        if(v_>maxpoint):
            return (False,"当前分值超过总分")
        else:
            return (True,Decimal(str(v_))*weight[subject_])
    else:
        if(value1 == "" or value1 is  None ):
            return (True,MissingExamination)
        else:
            try:
                float(value1)
            except:
                return (False,"数据错误")
        if(value1>maxpoint):
            return (False,"当前分值超过总分")
        else:
            return (True,Decimal(str(value1))*weight[subject_])
        
def runsql(sql):
    try:
        result_=cur.execute(sql)
        db.commit()
        log.debug(f"#执行成功# {sql} ")
        return result_
    except Exception as e:
        log.error((f"!执行失败! {sql} {e}"))
        db.rollback()
        return False
def runsqlmany(sql,data_):
    try:
        cur.executemany(sql,data_)
        db.commit()
        log.debug(f"#执行成功# {sql} ")
        return True
    except Exception as e:
        log.error((f"!执行失败! {sql}  {e}"))
        db.rollback()
        return False 

if __name__ == "__main__":
    print(colnames)
    print(subjectList)
    print("道德与法治" in list(subject_alias.keys()))
    print("英语" in list(SubjectMerger.keys()))
    for i in colnames:
        print(i)
    for i in subject:
        print(i)